package com.zyh.market.utils;


import com.alibaba.fastjson.JSON;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.zyh.market.constants.ResultCode;
import com.zyh.market.exception.ServiceException;
import org.springframework.web.multipart.MultipartFile;



/**
 * @author zhangyihua
 * @version 1.0
 * @description TODO
 * @date 2023/2/22 16:08
 */
//七牛云存储工具类
//@Component
public class QiniuUtils {
    //预览外链
    public static final String url = "http://127.0.0.1:9020/buckets";
    //Access Key
    private String accessKey = "iK3WbNhZqFSQ9qDJ87To";
    //Secret Key
    private String SecretKey = "1J6qJy6YG1TJgvVJbBUFrgLjx5EJFl7aVQ7VA1k1";
    //存储空间名称
    private String bucket = "reuse-market";

    /**
     * 上传文件到七牛云存储
     * @param file 要上传的文件
     * @param fileName 文件名
     * @return 上传是否成功
     * @throws ServiceException 如果上传失败，则抛出服务异常
     */
    public boolean upload(MultipartFile file, String fileName) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        //创建上传管理器
        UploadManager uploadManager = new UploadManager(cfg);
        //上传文件
        try {
            //生成上传凭证
            Auth auth = Auth.create(accessKey, SecretKey);
            String upToken = auth.uploadToken(bucket);
            //执行上传
            Response response = uploadManager.put(file.getBytes(), fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            return true;
        } catch (Exception ex) {
            throw new ServiceException(ResultCode.Fail);
        }
    }
}

